package com.hanbang.gycatering.property;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.hanbang.gangyu.R;
import com.hanbang.gycatering.adpater.PropertyAdapter;
import com.hanbang.gycatering.application.MyApplication;
import com.hanbang.gycatering.bean.PropertyBeanData;
import com.hanbang.gycatering.homepage.BaseActivity;
import com.hanbang.gycatering.property.PropertyfeeRecord.Myadapter;
import com.hanbang.gycatering.utils.HttpInterfaces;
import com.hanbang.gycatering.utils.MyLog;
import com.hanbang.gycatering.utils.MyRequestCallBack;
import com.hanbang.gycatering.utils.MyToast;
import com.hanbang.gycatering.utils.PagingHelp;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class PropertyfeeRecord extends BaseActivity implements OnClickListener {
	private PullToRefreshListView pfplistivew;
	private ArrayList<PropertyBeanData> propertyfeeDatas = new ArrayList<PropertyBeanData>();
	private PagingHelp pagingHelp = new PagingHelp();
	private boolean mIsSelectAll = false;
	private CheckBox mSelectAll;
	private TextView mDeleteRl, editTextView;
	// 被选中的个数
		private int selectCount = 0;
	private RelativeLayout rl_delete;
	private Myadapter myadapter;
	 // 当前listView是否处于删除模式 ,默认是正常显示模式.
	private boolean mIsDeleteModel = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		initAnim();
		setContentView(R.layout.propertyfeepay);
		initView();
		setTheClick();
	}

	private void initView() {
		// TODO Auto-generated method stub
		pfplistivew = (PullToRefreshListView) findViewById(R.id.pfplistivew);
		editTextView = (TextView) findViewById(R.id.right_text);
		mDeleteRl = (TextView) findViewById(R.id.main_delete_rl);
		rl_delete = (RelativeLayout) findViewById(R.id.rl_delete);
		mSelectAll = (CheckBox) findViewById(R.id.tv_select_all);
		((TextView) findViewById(R.id.top_bar_title)).setText("缴费记录");
		editTextView.setVisibility(View.VISIBLE);
		editTextView.setText("编辑");
		myadapter = new Myadapter(propertyfeeDatas);
		pfplistivew.setMode(Mode.BOTH);
		pfplistivew.setAdapter(myadapter);
		getPropertyFeeDatas();
	}

	private void setTheClick() {
		mSelectAll.setOnClickListener(this);
		mDeleteRl.setOnClickListener(this);
		editTextView.setOnClickListener(this);
		setBackArrows((ImageView) findViewById(R.id.top_bar_left_image));
		pfplistivew.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				if (mIsDeleteModel) {
					addDeleteDog(position - 1);
				} else {
					 
				}
				// TODO Auto-generated method stub
			}
		});
		pfplistivew.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				// TODO Auto-generated method stub
				propertyfeeDatas.clear();
				pagingHelp.clear();
				getPropertyFeeDatas();
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				// TODO Auto-generated method stub
				 
				getPropertyFeeDatas();
				  
			}
		});
	}

	private void getPropertyFeeDatas() {
		// TODO Auto-generated method stub
		MyLog.e("wuyefei", HttpInterfaces.propertylist+"&userphone="
						+ userData.getUserphone() + "&password="
						+ userData.getUserpassword()
						+ "&PageIndex=" + pagingHelp.getPageindex());
		((MyApplication) getApplicationContext()).httpUtils.send(
				HttpMethod.GET, HttpInterfaces.propertylist+"&userphone="
						+ userData.getUserphone() + "&password="
						+ userData.getUserpassword()
						+ "&PageIndex=" + pagingHelp.getPageindex(),
				new MyRequestCallBack<String>(PropertyfeeRecord.this,
						getString(R.string.loadding)) {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(
									responseInfo.result);
							int state=json.getInt("state");
							if (state == 1) {
								pagingHelp.setRecordCount(json
										.getInt("recordCount"));
								pagingHelp.setPageCount(json
										.getInt("pageCount"));
								JSONArray info = json.getJSONArray("info");
										 
								int j=0;
								for (j= pagingHelp.getCurrentCount(); j < info.length(); j++) {
									PropertyBeanData pbdata = new PropertyBeanData();
									pbdata.setId(info.getJSONObject(j)
											.getInt("id"));
									pbdata.setTitle(info.getJSONObject(j)
											.getString("money")+"元");
									pbdata.setTime(info.getJSONObject(j)
											.getString("time"));
									propertyfeeDatas.add(pbdata);
								}
								pagingHelp.isNextPaging(PropertyfeeRecord.this,
										info.length(), j);
							} else if(state==-100){
								 passwordIsError(false);
							}
							myadapter.notifyDataSetChanged();
						} catch (JSONException e) {
							e.printStackTrace();
							MyToast.show(PropertyfeeRecord.this, "获取数据失败",
									Toast.LENGTH_SHORT);
						}
						pfplistivew.onRefreshComplete();
					}
				});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.tv_select_all:
			if (mSelectAll.isChecked()) {
				addDeleteAllDogs();
			} else {
				clearCheckItem();
			}
			break;
		case R.id.main_delete_rl:
			deleteCheckItem();
			hideDeleteModel();
			break;
		case R.id.right_text:
			showDeleteModel();
			break;
		default:
			break;
		}
	}
	// 清空全部
		private void clearCheckItem() {
			Iterator<PropertyBeanData> iterator = propertyfeeDatas.iterator();
			while (iterator.hasNext()) {
				PropertyBeanData pbd = iterator.next();
				pbd.setChecked(false);
			}
			myadapter.setDatas(propertyfeeDatas);
			myadapter.showDeleteCheckBox();
			mIsDeleteModel = true;
			mIsSelectAll = false;
		}

		// 删除
		private void deleteCheckItem() {
			((MyApplication) getApplicationContext()).httpUtils.send(
					HttpMethod.GET, HttpInterfaces.propertydelete + "&password="
							+ userData.getUserpassword() + "&userphone="
							+ userData.getUserphone() + "&idval="
							+ getSeleteId(), new MyRequestCallBack<String>(
									PropertyfeeRecord.this, getString(R.string.loadding)) {
						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							super.onSuccess(responseInfo);
							try {
								JSONObject json = new JSONObject(
										responseInfo.result);
								int state = json.getInt("state");
								if (state == 1) {
									propertyfeeDatas.clear();
									pagingHelp.clear();
									MyToast.show(PropertyfeeRecord.this, "删除成功", Toast.LENGTH_SHORT);
									getPropertyFeeDatas();
								} else if (state == -100) {
									passwordIsError(false);
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}

						}
					});
//			Iterator<PropertyBeanData> iterator = propertyfeeDatas.iterator();
//			int count = 0;
//			while (iterator.hasNext()) {
//				PropertyBeanData pbd = iterator.next();
//				if (pbd.isChecked()) {
//					count++;
//					iterator.remove();
//				}
//			}
//			MyToast.show(PropertyfeeRecord.this, "删除了" + count + "条", Toast.LENGTH_SHORT);
		}

		// 添加删除item
		private void addDeleteDog(int position) {
			PropertyBeanData pbd = (PropertyBeanData) propertyfeeDatas.get(position);
			if (pbd.isChecked()) {
				pbd.setChecked(false);
			} else {
				pbd.setChecked(true);
			}
			myadapter.setDatas(propertyfeeDatas);
			myadapter.showDeleteCheckBox();
			mIsDeleteModel = true;
		}

		// 全部选中
		private void addDeleteAllDogs() {
			Iterator<PropertyBeanData> iterator = propertyfeeDatas.iterator();
			while (iterator.hasNext()) {
				PropertyBeanData pbd = iterator.next();
					pbd.setChecked(true);
			}
			myadapter.setDatas(propertyfeeDatas);
			myadapter.showDeleteCheckBox();
			mIsDeleteModel = true;
			mIsSelectAll = true;
		}
		// 展示编辑模式
			private void showDeleteModel() {
				mSelectAll.setChecked(false);
				mIsDeleteModel = true;
				editTextView.setVisibility(View.GONE);
				setAnim();
				// PropertyBeanData pbd = (PropertyBeanData) propertyfeeDatas.get(position);
				// pbd.setChecked(true);
				myadapter.setDatas(propertyfeeDatas);
				myadapter.showDeleteCheckBox();
				
			}

		// 隐藏编辑模式，回到正常显示listView
		private void hideDeleteModel() {
			mIsDeleteModel = false;
			editTextView.setVisibility(View.VISIBLE);
			setAnim();
			Iterator<PropertyBeanData> iterator = propertyfeeDatas.iterator();
			while (iterator.hasNext()) {
				PropertyBeanData pbd = iterator.next();
				pbd.setChecked(false);
			}
			myadapter.hideDeleteCheckBox();
			myadapter.notifyDataSetChanged();
		}

		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event) {
			if (myadapter == null) {
				return super.onKeyDown(keyCode, event);
			}
			if (keyCode == KeyEvent.KEYCODE_BACK && mIsDeleteModel) {
				hideDeleteModel();
				return true;
			}
			return super.onKeyDown(keyCode, event);
		}

		public class Myadapter extends BaseAdapter {
			PropertyBeanData entity;
			Bitmap bit;

			private List<PropertyBeanData> coll;
			private boolean mIsShowDeleteCheckBox;

			public Myadapter(List<PropertyBeanData> coll) {
				this.coll = coll;
			}

			public void setDatas(List<PropertyBeanData> colls) {
				this.coll = colls;
			}

			public int getCount() {
				return coll.size();
			}

			public Object getItem(int position) {
				return coll.get(position);
			}

			public long getItemId(int position) {
				return position;
			}

			@SuppressLint("InflateParams") @Override
			public View getView(int position, View convertView, ViewGroup parent) {
				MyLog.e("getView", position + "");
				ViewHolder holder = null;
				PropertyBeanData data = coll.get(position);
				if (convertView == null) {
					holder = new ViewHolder();
					convertView = getLayoutInflater().inflate(
							R.layout.item_property, null);
					holder.title = (TextView) convertView
							.findViewById(R.id.item_left);
					holder.time = (TextView) convertView
							.findViewById(R.id.item_right);
					holder.cb = (CheckBox) convertView
							.findViewById(R.id.item_propertycb);
					convertView.setTag(holder);
				} else {
					holder = (ViewHolder) convertView.getTag();
				}
				if (mIsShowDeleteCheckBox) {
					holder.cb.setVisibility(View.VISIBLE);
					holder.cb.setChecked(coll.get(position).isChecked());
					if (coll.get(position).isChecked()) {
						if (selectCount < propertyfeeDatas.size()) {
							selectCount++;
						}
					} else {
						if (selectCount > 0) {
							selectCount--;
						}
					}
					if (selectCount >= propertyfeeDatas.size()) {
						selectCount = propertyfeeDatas.size();
						mSelectAll.setSelected(true);
					} else {
						mSelectAll.setSelected(false);
					}
				} else {
					holder.cb.setVisibility(View.GONE);
				}
				holder.title.setText(data.getTitle());
					holder.time.setText(data.getTime());
				 
				return convertView;
			}

			private class ViewHolder {
				TextView title = null;
				TextView time = null;
				CheckBox cb;
			}

			public void showDeleteCheckBox() {
				mIsShowDeleteCheckBox = true;
				notifyDataSetChanged();
			}

			public void hideDeleteCheckBox() {
				mIsShowDeleteCheckBox = false;
			}
		}
		private Animation showAction = null, hiddenAction = null;
		private void initAnim() {
			showAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
					Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
					1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
			showAction.setDuration(150);
			hiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
					Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
					0.0f, Animation.RELATIVE_TO_SELF, 1.0f);
			hiddenAction.setDuration(150);
		}
		private void setAnim() {
			rl_delete.clearAnimation();
			if(mIsDeleteModel){
				rl_delete.setVisibility(View.VISIBLE);
				rl_delete.startAnimation(showAction);
			}else{
				rl_delete.setVisibility(View.GONE);
				rl_delete.startAnimation(hiddenAction);
			}
		}
//		获得ID字符串
		private String getSeleteId() {
			// 遍历出id 2,4,6
			StringBuilder id = new StringBuilder();

			for (PropertyBeanData data : propertyfeeDatas) {
				if (data.isChecked()) {
					id.append(data.getId() + ",");

				}
			}
			if (id.length() > 0) {
				id.delete(id.length() - 1, id.length());
			}
			MyLog.e("getSeleteId", id.toString());
			return id.toString();
		}

}
